package org.webdb.webapp.jackson;

import java.io.IOException;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;
import org.postgis.Geometry;
import org.postgis.LineString;
import org.postgis.MultiLineString;
import org.postgis.MultiPolygon;
import org.postgis.PGgeometry;
import org.postgis.Point;
import org.postgis.Polygon;

public class POSTGISSerializer extends JsonSerializer<PGgeometry> {

    private PointJSONSerializer pointSerializer;
    private LineStringJSONSerializer lineStringSerializer;
    private PointComposedJSONSerializer pointComposedSerializer;
    private PolygonJSONSerializer polygonSerializer;
    private MultiLineStringSerializer multiLineStringSerializer;
    private MultiPolygonSerializer multiPolygonSerializer;

    public POSTGISSerializer() {
        pointSerializer = new PointJSONSerializer();
        pointComposedSerializer = new PointComposedJSONSerializer(
                pointSerializer);
        lineStringSerializer = new LineStringJSONSerializer(
                pointComposedSerializer);
        polygonSerializer = new PolygonJSONSerializer(pointComposedSerializer);
        multiLineStringSerializer = new MultiLineStringSerializer(
                pointComposedSerializer);
        multiPolygonSerializer = new MultiPolygonSerializer(polygonSerializer);
    }

    @Override
    public void serialize(PGgeometry value, JsonGenerator jgen,
            SerializerProvider provider) throws IOException,
            JsonProcessingException {

        switch (value.getGeoType()) {
        case Geometry.POINT:
            pointSerializer.serialize((Point) value.getGeometry(), jgen,
                    provider);
            break;
        case Geometry.LINESTRING:
            lineStringSerializer.serialize((LineString) value.getGeometry(),
                    jgen, provider);
            break;
        case Geometry.POLYGON:
            polygonSerializer.serialize((Polygon) value.getGeometry(), jgen,
                    provider);
            break;
        case Geometry.MULTILINESTRING:
            multiLineStringSerializer.serialize(
                    (MultiLineString) value.getGeometry(), jgen, provider);
            break;
        case Geometry.MULTIPOLYGON:
            multiPolygonSerializer.serialize(
                    (MultiPolygon) value.getGeometry(), jgen, provider);
        default:
            throw new UnsupportedGeometryTypeException(value.getType());
        }
    }

    @Override
    public Class<PGgeometry> handledType() {
        return PGgeometry.class;
    }

}
